package hu.test.atacama;

import android.accounts.Account;
import android.accounts.AccountManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceActivity;
import android.preference.PreferenceManager;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;

public class AtacamaSettings extends PreferenceActivity {

	AccountManager am;
	Account[] accounts;
	IntentFilter commServIntentFilter, commServErrorIntentFilter;
	CommServiceReceiver commServiceReceiver = new CommServiceReceiver();
	final Intent commServiceIntent = new Intent();
	Common common;

	@SuppressWarnings("deprecation")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
		super.onCreate(savedInstanceState);

		am = AccountManager.get(this);
		accounts = am.getAccountsByType("com.google");
		addPreferencesFromResource(R.xml.prefs);

		common = Common.getInstance(this);
		commServiceIntent.setClass(getApplicationContext(), CommService.class);
		commServIntentFilter = new IntentFilter(CommService.COMMSERVICE_DONE);
		commServErrorIntentFilter = new IntentFilter(CommService.COMMSERVICE_ERROR);
	}

	@Override
	protected void onPause() {
		super.onPause();
		unregisterReceiver(commServiceReceiver);
		unregisterReceiver(registrationDone);
		unregisterReceiver(commServiceError);
	}

	@Override
	protected void onResume() {
		super.onResume();
		registerReceiver(commServiceReceiver, commServIntentFilter);
		registerReceiver(registrationDone, commServIntentFilter);
		registerReceiver(commServiceError, commServErrorIntentFilter);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.atacama_settings, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.settings_back:
			finish();
			return true;
		case R.id.settings_register_device:
			registerDevice();
			return true;
		case R.id.settings_load_defaults:
			SharedPreferences prefs = PreferenceManager
					.getDefaultSharedPreferences(this);
			prefs.edit().clear().commit();
			refreshPreferences();
			return true;
		case R.id.settings_choose_sender:
			registerForContextMenu(getCurrentFocus());
			openContextMenu(getCurrentFocus());
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		super.onCreateContextMenu(menu, v, menuInfo);
		menu.setHeaderTitle(getString(R.string.menu_title_sender));
		for (int i = 0; i < accounts.length; i++) {
			menu.add(Menu.NONE, i, Menu.NONE, accounts[i].name);
		}
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		String senderID = accounts[item.getItemId()].name;
		SharedPreferences prefs = PreferenceManager
				.getDefaultSharedPreferences(this);
		prefs.edit().putString(getString(R.string.key_sender_id), senderID)
				.commit();
		refreshPreferences();
		return super.onContextItemSelected(item);
	}

	private void registerDevice() {
		if (common.getSenderID().equals(getString(R.string.default_sender_id))) {
			common.displayToast(getString(R.string.menu_sender_id_not_set));
		} else {
			setProgressBarIndeterminateVisibility(true);

			String gpsData = "None";
			Long timeStamp = System.currentTimeMillis();
			DataFromDevice dataFromDevice = new DataFromDevice(
					common.getDeviceType(), common.getSenderID(), common.getSerialNumber(),
					gpsData, timeStamp, Common.COMMAND_REGISTER);

			commServiceIntent.putExtra("dataFromDevice", dataFromDevice);
			commServiceIntent.putExtra("startingMessage",
					getString(R.string.message_registration_started));

			startService(commServiceIntent);
		}
	}

	@SuppressWarnings("deprecation")
	private void refreshPreferences() {
		setPreferenceScreen(null);
		addPreferencesFromResource(R.xml.prefs);
	}

	private BroadcastReceiver registrationDone = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			setProgressBarIndeterminateVisibility(false);
		}
	};
	
	private BroadcastReceiver commServiceError = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			setProgressBarIndeterminateVisibility(false);
			common.displayToast("Commservice error");
		}
	};
}